package com.ruoyi.web.cp.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.web.core.config.ConfigLoader;
import com.ruoyi.web.cp.model.Game;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class FbService {
    @Autowired
    private HttpService httpService;
    @Autowired
    private ConfigLoader configLoader;
    @Autowired
    private WinxinService winxinService;

    /**
     * @Description: 获取fb列表
     * @Author: xiesm
     * @Date: 2025/3/21
     */
    public List<String> getFbList() {
        int num = 1;
        JSONObject jsonObject = httpService.sendFbList(num);
        JSONObject data = jsonObject.getJSONObject("data");
        Integer total = data.getInteger("total");
        JSONArray records = data.getJSONArray("records");
        for (int i = 0; i < total / 100; i++) {
            num++;
            System.out.println("num:" + num);
            JSONObject json = httpService.sendFbList(num);
            records.addAll(json.getJSONObject("data").getJSONArray("records"));
        }
        return parseResult(records);
    }

    public List<String> parseResult(JSONArray records) {
        List<String> list = new ArrayList<>();
        String text = "{}\t{}\t{}\t{}\t{}";
        for (int i = 0; i < records.size(); i++) {
            try {
                JSONObject record = records.getJSONObject(i);
                Long bt = record.getLong("bt");
                String id = record.getString("id");
                String date = DateUtil.format(new Date(bt), "yyyy-MM-dd HH:mm:ss");
                JSONArray ts = record.getJSONArray("ts");
                String name1 = ts.getJSONObject(0).getString("na");
                String name2 = ts.getJSONObject(1).getString("na");
                String lg = record.getJSONObject("lg").getString("na");
                String str = StrUtil.format(text, id, lg, date, name1, name2).replace("\n", "");
                list.add(str);
            } catch (Exception e) {
                log.error("解析异常：{}", e.getMessage());
            }
        }
        FileUtil.writeLines(list, configLoader.getRmPath() + "fb-game.txt", "utf8");
        return list;
    }

    private static List<String> cleanFileNames = Arrays.asList(
            "fb-gameScore.txt",
            "fb-gameScore-half.txt"
    );

    public void getFbDetail() {
        for (int i = 0; i < cleanFileNames.size(); i++) {
            FileUtils.clearFile(configLoader.getRmPath() + cleanFileNames.get(i));
        }

        List<String> ids = FileUtil.readLines(configLoader.getRmPath() + "fb-game.txt", "utf8");
        String text = "{}\t{}";
        List<String> list = new ArrayList<>();
        List<String> listHalf = new ArrayList<>();

        for (int i = 0; i < ids.size(); i++) {
            try {
                writeScore(ids, i, text, list, listHalf);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    @SafeVarargs
    private final void writeScore(List<String> ids, int i, String text, List<String>... lists) {
        String str = ids.get(i);
        for (int k = 0; k < lists.length; k++) {
            lists[k].clear();
            lists[k].add(str);
        }
        String[] split = str.split("\\t");
        JSONObject res = httpService.sendFbDetail(split[0], str);
        JSONArray mgs = res.getJSONObject("data").getJSONArray("mg");

        JSONObject cache = new JSONObject();
        for (int j = 0; j < mgs.size(); j++) {
            JSONObject mg = mgs.getJSONObject(j);
            String nm = mg.getString("nm");
            if ("双方均有进球".equals(nm)) {
                JSONArray mks = mg.getJSONArray("mks");
                for (int k = 0; k < mks.size(); k++) {
                    JSONObject mk = mks.getJSONObject(k);
                    JSONArray ops = mk.getJSONArray("op");
                    for (int l = 0; l < ops.size(); l++) {
                        JSONObject op = ops.getJSONObject(l);
                        if ("是".equals(op.getString("nm"))) {
                            cache.put("双进", op.getString("od"));
                        }
                    }
                }
            }
            if ("大/小".equals(nm)) {
                JSONArray mks = mg.getJSONArray("mks");
                for (int k = 0; k < mks.size(); k++) {
                    JSONObject mk = mks.getJSONObject(k);
                    String mbl = mk.getString("mbl");
                    if (!"1".equals(mbl)) {
                        continue;
                    }
                    JSONArray ops = mk.getJSONArray("op");
                    cache.put("大小", ops.getJSONObject(0).getString("li"));
                }
            }
            if ("让球".equals(nm)) {
                JSONArray mks = mg.getJSONArray("mks");
                for (int k = 0; k < mks.size(); k++) {
                    JSONObject mk = mks.getJSONObject(k);
                    String mbl = mk.getString("mbl");
                    if (!"1".equals(mbl)) {
                        continue;
                    }
                    JSONArray ops = mk.getJSONArray("op");
                    cache.put("亚盘", ops.getJSONObject(0).getString("li"));
                }
            }
        }

        for (int j = 0; j < mgs.size(); j++) {
            JSONObject mg = mgs.getJSONObject(j);
            String nm = mg.getString("nm");
            if ("波胆".equals(nm)) {
                getStr(lists[0], text, mg, "na", "od");
            }
            if ("波胆-上半场".equals(nm)) {
                getStr(lists[1], text, mg, "na", "od");
            }
        }
        if (CollUtil.isNotEmpty(lists[0]) && cache.get("双进") != null) {
            lists[0].add("双进\t" + cache.get("双进"));
        }
        if (CollUtil.isNotEmpty(lists[0]) && cache.get("大小") != null) {
            lists[0].add("大小\t" + cache.get("大小"));
        }
        if (CollUtil.isNotEmpty(lists[0]) && cache.get("亚盘") != null) {
            String yapan = cache.getString("亚盘");
            yapan = yapan.replace("-", "让").replace("+", "受让");
            lists[0].add(StrUtil.format("亚盘\t{}", yapan));
        }
        FileUtil.writeLines(lists[0], configLoader.getRmPath() + "fb-gameScore.txt", "utf8", true);
        FileUtil.writeLines(lists[1], configLoader.getRmPath() + "fb-gameScore-half.txt", "utf8", true);
    }

    private void getStr(List<String> list2, String text, JSONObject mg, String key1, String key2) {
        JSONArray ops = mg.getJSONArray("mks").getJSONObject(0).getJSONArray("op");
        for (int k = 0; k < ops.size(); k++) {
            JSONObject op = ops.getJSONObject(k);
            String na = op.getString(key1).trim().replace(" ", "");
            List<String> scores = Arrays.asList("其他", "4-0", "4-1", "4-2", "4-3", "4-4", "0-4", "1-4", "2-4", "3-4");
            if (scores.contains(na)) {
                continue;
            }
            String od = op.getString(key2);
            if (!"null".equals(od) && od != null) {
                String s = StrUtil.format(text, na, od);
                list2.add(s);
            }
        }
    }
}
